package org.ainlolcat.ainscience.UI;

import org.ainlolcat.ainscience.Controller;
import org.ainlolcat.ainscience.UpdateListener;
import org.ainlolcat.ainscience.entity.Entity;
import org.ainlolcat.ainscience.project.VisibleEntityFilter;
import org.apache.log4j.Logger;

import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: ain
 * Date: 11.02.12
 * Time: 3:14
 * To change this template use File | Settings | File Templates.
 */
public class EntityListModel implements ListModel, UpdateListener{
    private static Logger log = Logger.getLogger(EntityListModel.class);
    List<ListDataListener> listenerList;

    private List<String> getCurrentSet(){
        Set<String> namesSet =  Controller.getInstance().getProject().getFilteredEntityNames(new VisibleEntityFilter());
        String[] names = namesSet.toArray(new String[namesSet.size()]) ;
        Arrays.sort(names);
        return Arrays.asList(names); 
    } 
    
    public EntityListModel(){
        listenerList = new ArrayList<ListDataListener>();
        Controller.getInstance().addUpdateListener(this);
    }

    public int getSize() {
        try{
            return getCurrentSet().size();
        } catch(Exception e) {

        }
        return 0;
    }

    public Object getElementAt(int index) {
        return getCurrentSet().get(index);
    }

    public void addListDataListener(ListDataListener l) {
        if (!listenerList.contains(l)){
            listenerList.add(l);
        }
    }

    public void removeListDataListener(ListDataListener l) {
        if (listenerList.contains(l)){
            listenerList.remove(l);
        }
    }

    public void onProjectUpdate() {
        log.debug("Update event income for project");
        for (ListDataListener ldl: listenerList){
            ldl.contentsChanged(new ListDataEvent(this,ListDataEvent.CONTENTS_CHANGED,0,getSize()));
        }
    }

    public void onEntityUpdate(Entity entity, int action) {
        log.debug("Update event income for " + entity.getName());
        for (ListDataListener ldl: listenerList){
            ldl.contentsChanged(new ListDataEvent(this,ListDataEvent.CONTENTS_CHANGED,0,getSize()));
        }
    }
}
